// elder/publish/publish.js
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    width:'',
    textContent:'',
    fileList: 
    [
      
    ],
    pictureList:[]
  },

  afterRead(event) {
    var fileList = this.data.fileList
    const { file } = event.detail;
    console.log(file)
    for(var i in file){
      fileList.push(file[i])
    }
    this.setData({
      fileList:fileList
    })
    
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var windowWidth = wx.getSystemInfoSync().windowWidth
    this.setData({
      width:(windowWidth-65)/3
    })
    
  },
  bindinput(e){
    this.setData({
      textContent:e.detail.value
    })
  },
 
  setPicture(){
    const textContent = this.data.textContent
    if(this.data.fileList.length==0){
      Toast('请上传图片')
      return
    }
    wx.showLoading({
      title: '发表中',
    })
    if(this.data.fileList.length===0){
      this.publish()
    }
    
    const that = this
    for (var i in this.data.fileList){
      var file = this.data.fileList[i]
      wx.uploadFile({
        url: 'https://zhixiao.site:8080/goodMemory/upload', 
        filePath: file.url,
        name: 'file',
        formData: { user: 'test' },
        success(res) {
          console.log(res)
          var url = res.data.slice(32,res.data.length-3)
          console.log(url)
          var pictureList = that.data.pictureList
          pictureList.push(url)
          that.setData({
            pictureList:pictureList
          })
        },
        complete(res){
          //处理异步问题
          if (that.data.pictureList.length === that.data.fileList.length){
            that.publish()
          }
        }
      });
    }
  },
  publish(){
    var imageUrl = ''
    const pictureList = this.data.pictureList
    if(pictureList.length!=0){
      imageUrl = this.data.pictureList.join(";")
      console.log(imageUrl)
    }
    wx.request({
      url: 'https://zhixiao.site:8080/goodMemory/add',
      data:
      {
        userId:wx.getStorageSync('userid'),
        photoUrls:imageUrl,
        content:this.data.textContent
      },
      success:(res)=>{
        console.log(res)
        Toast('发表成功')
      },
      complete:(res)=>{
        wx.hideLoading()
        wx.setStorageSync('update1', 1)
        wx.navigateBack({
          delta:1
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})